<template>
    <el-dialog title="组卷" v-model="visible" width="75%" :close-on-click-modal="false" draggable>
        <el-container>
            <el-aside width="200px">
                <el-card style="margin: 5px 15px 10px 20px">
                    <el-text style="font-weight: bold;font-size: 20px">随机组卷</el-text> <br />
                    <el-text
                        style="font-weight: bold;font-size: 15px">试题总数:{{ queryForm.examQuestionNum }}道</el-text><br />
                    <el-text style="font-weight: bold;font-size: 15px">试卷总分:{{ queryForm.examMarkSum }}分</el-text><br />
                    <el-text style="font-weight: bold;font-size: 15px;color: red">试卷总分必须为100分，否则无法创建试卷</el-text><br />
                    <!--                    <el-button type="primary" style="margin-top: 10px" @click="submitBtn">保存本试卷</el-button>-->
                </el-card>
            </el-aside>
            <el-main>
                <el-row v-show="showSearch">
                    <el-form :model="queryForm" ref="dataFormRef" :rules="dataRules" :inline="true"
                        @keyup.enter="getDataList">
                        <el-row>
                            <el-form-item label="参考组织" prop="partOrgId1">
                                <el-cascader v-model="queryForm.partOrgId1" ref="cascaderAddr" style="width: 500px"
                                    disabled placeholder="请选择标签"
                                    :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
                                    :options="options1" clearable filterable>
                                </el-cascader>
                            </el-form-item>
                            <el-form-item label="专业名称" prop="zymcId">
                                <el-select @change="getItem3" v-model="queryForm.zymcId" filterable clearable multiple
                                    collapse-tags collapse-tags-tooltip placeholder="请选择" style="width: 240px">
                                    <el-option v-for="item in options2" :key="item.zymcId" :label="item.zymcName"
                                        :value="item.zymcId" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="关键点" prop="keyId">
                                <el-select @change="getItem2" v-model="queryForm.keyId" filterable clearable multiple
                                    collapse-tags collapse-tags-tooltip placeholder="请选择" style="width: 240px">
                                    <el-option v-for="item in keypointsListData" :key="item.keyId"
                                        :label="item.zymcName + '-' + item.keyPoint" :value="item.keyId" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="是否随机组卷" prop="isRandom">
                                <el-switch v-model="queryForm.isRandom" />
                            </el-form-item>
                            <el-form-item label="">
                                <el-button type="primary" size="mini" @click="getList"
                                    style="margin-left: 10px">查询总题数</el-button>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="组卷名称" prop="examInfoName">
                                <el-input v-model="queryForm.examInfoName" placeholder="请输入考试标签" />
                            </el-form-item>
                        </el-row>
                    </el-form>
                </el-row>
                <el-row>
                </el-row>
                <div style="margin-bottom: 20px;margin-left: 10px">
                    <el-text style="font-size: 20px">试题列表</el-text>
                    <el-text style="color: red"
                        v-if="mark">(单选题:共{{ problemsNumberList.radio_num }}道,多选题:共{{ problemsNumberList.multi_num }}道,判断题:共{{ problemsNumberList.judge_num }}道,
                        填空题:共{{ problemsNumberList.fill_num }}道,简答题:共{{ problemsNumberList.answer_num }}道 )</el-text>
                </div>
                <el-table :data="info" v-loading="loading" border :row-class-name="rowOrderItemIndex"
                    @selection-change="handleOrderItemSelectionChange" ref="OrderItem"
                    :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                    @sort-change="sortChangeHandle">
                    <el-table-column type="selection" width="40" align="center" />
                    <el-table-column type="index" label="序号" width="80" />
                    <el-table-column prop="questionType" label="题型" show-overflow-tooltip>
                        <template #default="scope">
                            <el-select v-model="scope.row.questionType" placeholder="请选择题型" clearable>
                                <el-option :label="item.label" :value="item.value"
                                    v-for="(item, index) in tkgl_topic_type" :key="index"
                                    @click="checkNumber(scope.row)"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="difficulty" label="难易程度" show-overflow-tooltip>
                        <template #default="scope">
                            <el-input-number v-model="scope.row.difficulty" :min="1" :max="20"
                                @click="checkNumber(scope.row)" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="questionNum" label="题目数量" show-overflow-tooltip>
                        <template #default="scope">
                            <el-input-number v-model="scope.row.questionNum" :min="1" :max="100"
                                @click="checkNumber(scope.row)" />
                        </template>
                    </el-table-column>
                    <!--                    <el-table-column label="操作" align="center">-->
                    <!--                        <template #default="scope">-->
                    <!--                            <el-button icon="RefreshLeft"  text type="primary" v-auth="'train_kszlFile_del'" @click="checkNumber(scope.row)"> 查询题库总数</el-button>-->
                    <!--                        </template>-->
                    <!--                    </el-table-column>-->
                    <el-table-column prop="questionSum" label="题库总数" show-overflow-tooltip />
                    <el-table-column prop="mark" label="分值(每道)" show-overflow-tooltip>
                        <template #default="scope">
                            <el-input-number v-model="scope.row.mark" :min="1" :max="25" @click="getScore"
                                @blur="getScore()" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="markSum" label="总分值" show-overflow-tooltip :formatter="formatTotalScore" />

                </el-table>
                <el-button type="danger" icon="delete" style="margin-top: 10px" size="mini"
                    @click="handleDeleteOrderItem">删除</el-button>
                <el-button type="primary" icon="el-icon-plus" style="margin-top: 10px" size="mini"
                    @click="handleAddOrderItem">添加题型</el-button>

                <el-button type="danger" style="margin-top: 10px" size="mini" @click="submitBtn"
                    :disabled="started1">保存试卷并关闭</el-button>
                <!-- 题目数量校验  -->
                <el-dialog v-model="centerDialogVisible1" width="20%">
                    <el-text style="color: red;font-weight: bold;font-size: 22px">{{ checkMsg }}</el-text>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button type="primary" style="margin-left: -10px;margin-top: -10px"
                                @click="centerDialogVisible1 = false">确认</el-button>
                        </span>
                    </template>
                </el-dialog>
                <!-- 试卷分数校验  -->
                <el-dialog v-model="centerDialogVisible2" width="20%">
                    <el-text style="color: red;font-weight: bold">试卷总分必须为100分，否则创建失败</el-text>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button type="primary" style="margin-left: -10px;margin-top: -10px"
                                @click="centerDialogVisible2 = false">确认</el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </el-dialog>
</template>

<script setup lang="ts" name="ksglExamListDialog">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { useDict } from '/@/hooks/dict';
import { useMessage, useMessageBox } from "/@/hooks/message";
import { rule } from '/@/utils/validate';
import { ref } from "vue";
import { defineEmits } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { deptTree } from "/@/api/train/kszlData";
import { professionalnameList } from "/@/api/train/jnglProfessionLevel";
import { keypointsList, putObj } from "/@/api/train/kszlFile";
import { fetchList } from "/@/api/train/ksglExamInfo";
import { delObjs } from "/@/api/train/kszlQuery";
import { problemsNumber, problemsNumberCheck, submit, getKeyPointListByZymcIds, edit, getexamInfoId, delChildObjs, removeChild } from "/@/api/train/ksglExamList";
const centerDialogVisible1 = ref(false)
const centerDialogVisible2 = ref(false)
const showSearch = ref(true)
const info = ref([{}]);
const checkedOrderItem = ref<any>(null);
// 定义变量内容
const dataFormRef = ref();
const flag1 = ref();
const examInfoId = ref();
const selectionId = ref({});
const OrderItem = ref();
const checkMsg = ref();
const visible = ref(false)
const mark = ref(false)
const loading = ref(false)
const dataList = ref<any[]>([]); // 根据你的数据结构来定义类型
// 定义字典
const { tkgl_topic_type } = useDict('tkgl_topic_type')
// 提交表单数据
const form = reactive({
    difficulty: '',
    questionNum: '',
    mark: ''
});
const cascaderAddr = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);
let problemsNumberList = reactive({});
//关键点
const keypointsListData = reactive([{}])
const queryForm = reactive({
    ksglExamDetailsList: [],
    isRandom: true,
    examQuestionNum: 0,
    examMarkSum: 0,
    difficulty: 1,
    questionNum: 1,
    mark: 1,
    markSum: 1,
})
const state: BasicTableProps = reactive<BasicTableProps>({
    queryForm: {},
    pageList: fetchList
})
//  table hook
const {
    getDataList,
    currentChangeHandle,
    sizeChangeHandle,
    sortChangeHandle,
    downBlobFile,
    tableStyle
} = useTable(state)
//学习组织数据
const options1 = ref<any[]>([]);
const started1 = ref(false);
//专业名称数据
const options2 = reactive([{}])
const emit = defineEmits(['parentsEmit']);
// 定义校验规则
const dataRules = ref({
    zymcId: [{ required: true, message: '考试名称不能为空', trigger: 'blur' }],
    keyId: [{ required: true, message: '关键点不能为空', trigger: 'blur' }],
    isRandom: [{ required: true, message: '是否组卷不能为空', trigger: 'blur' }],
    examInfoName: [{ required: true, message: '组卷名称不能为空', trigger: 'blur' }],
})
const backId = ref()
onMounted(() => {
    deptTreeList()
    getProfessionalName()
})
// 打开弹窗
const openDialog = (groupId: string, groupName: string, processedPKPosts: any, examPaperId: string, flag: number, examId: string) => {
    nextTick(() => {
        started1.value = false
        dataFormRef.value?.resetFields();
        info.value.length = 0
        queryForm.examQuestionNum = 0
        queryForm.examMarkSum = 0
        queryForm.partOrgId1 = groupId
        queryForm.partPostId = processedPKPosts
        queryForm.partOrgId = groupId.join('/')
        queryForm.partOrgName = groupName.join('/')
        examInfoId.value = examPaperId
        flag1.value = flag
        if (flag1.value == 1) {
            mark.value = true
            let id = { examInfoId: examPaperId }
            getexamInfoId(id).then((res => {
                // console.log('res',res)
                Object.assign(queryForm, res.data);
                queryForm.examId = examId
                Object.assign(info.value, queryForm.ksglExamDetailsList);
                deptTreeList()
                getProfessionalName()
                getKeypointsList()
                getScore()
                getList()
            }))
        } else {
            mark.value = false
        }
        // console.log('queryForm',queryForm)
        visible.value = true
    });
};
//查询
const getList = () => {
    problemsNumber(queryForm).then((res) => {
        Object.assign(problemsNumberList, res.data)
        mark.value = true
    })
}
const getScore = () => {
    // console.log('info11111111----',info.value,queryForm.ksglExamDetailsList)
    queryForm.examQuestionNum = 0;
    queryForm.examMarkSum = 0;
    info.value.forEach(item => {
        // console.log('item---', item.questionNum,item.markSum)
        queryForm.examQuestionNum += item.questionNum;
        queryForm.examMarkSum += item.markSum;
    })
}
const checkNumber = (row: any) => {
    if (row.questionType !== undefined && row.questionNum !== undefined && row.difficulty !== undefined) {
        queryForm.ksglExamDetailsList.push(row)
        if (queryForm.ksglExamDetailsList.length > 0) {
            problemsNumberCheck(queryForm).then((res) => {
                row.questionSum = res.data
                // 处理接口返回的响应
            }).catch((error) => {
                if (error.msg !== null) {
                    checkMsg.value = error.msg
                    centerDialogVisible1.value = true
                    if (error.data !== 0) {
                        row.questionSum = error.data
                    } else {
                        row.questionSum = 0
                    }
                }
                // 处理接口调用错误
                console.error('接口调用失败：', error);
            });
        }
        queryForm.ksglExamDetailsList.length = 0
    } else {
        console.log('不能调用接口，因为至少有一个属性是undefined。');
    }
    getScore()
}
// 为每一行数据添加序号的方法
const rowOrderItemIndex = ({ row, rowIndex }: { row: any; rowIndex: number }) => {
    row.index = rowIndex + 1; // 给每一行添加一个 'index' 属性，值为序号（从1开始）
};
/** (子)添加按钮操作 */
const handleAddOrderItem = () => {
    let obj = {};
    obj.questionType = "";
    obj.questionNum = 1;
    obj.questionSum = ""
    obj.mark = 1
    obj.markSum = 1;
    obj.difficulty = 1;
    info.value.push(obj);
}
// 处理单选框选中数据
const handleOrderItemSelectionChange = (selection: any[]) => {
    selectionId.value = selection[0]
    console.log('selectionId.value', selectionId.value)
    if (selection.length > 1) {
        // 如果选择了多个项，则清除所有选择并只选择最后一个
        OrderItem.value?.clearSelection();
        if (selection.length > 0) {
            OrderItem.value?.toggleRowSelection(selection.pop());
        }
    } else if (selection.length === 1) {
        // 如果只选择了一个项，则更新选中项
        checkedOrderItem.value = selection[0];
    } else {
        // 如果没有选择任何项，则清除选中项
        checkedOrderItem.value = null;
    }
};
// 处理删除操作
const handleDeleteOrderItem = async () => {
    if (selectionId.value.id) {
        let srt = 'ids=' + selectionId.value.id + '&examId=' + queryForm.examId
        removeChild(srt)
    }
    if (!checkedOrderItem.value) {
        ElMessage.warning('请先选择要删除的站点(子)数据');
        return;
    }
    const confirmResult = await ElMessageBox.confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    });
    if (confirmResult === 'confirm') {
        const index = info.value.findIndex(item => item === checkedOrderItem.value);
        if (index !== -1) {
            info.value.splice(index, 1);
            // console.log(info.value,'info.value')
            getScore()
            ElMessage.success('删除成功');
        } else {
            ElMessage.warning('选中的项不存在于数据列表中');
        }
    }
};
//保存
const submitBtn = () => {
    console.log('queryForm.examId', queryForm.examId)
    queryForm.ksglExamDetailsList.length = 0
    queryForm.examInfoId = examInfoId.value
    Object.assign(queryForm.ksglExamDetailsList, info.value);
    dataFormRef.value?.validate((valid: any) => {
        if (valid) {

            if (queryForm.examMarkSum !== 100) {
                centerDialogVisible2.value = true
            } else if (queryForm.examInfoName == undefined) {
                ElMessage({
                    message: '组卷名称不能为空',
                    type: 'warning',
                })
            } else {
                started1.value = true
                //新建组卷-------保存
                if (flag1.value == 0) {
                    submit(queryForm).then((res) => {
                        ElMessage({
                            message: '创建成功',
                            type: 'success',
                        })
                        backId.value = res.data
                        let id = backId.value
                        let name = queryForm.examInfoName
                        let send = { name, id }
                        //给父组件传值
                        emit('parentsEmit', send);
                        visible.value = false
                    }).catch((error) => {
                        if (error.msg !== null) {
                            checkMsg.value = error.msg
                            centerDialogVisible1.value = true
                        }
                    });
                } else {
                    //修改组卷-------保存
                    edit(queryForm).then((res) => {
                        // ElMessage({
                        //     message: '修改成功',
                        //     type: 'success',
                        // })
                        let name = queryForm.examInfoName
                        let send = { name }
                        //给父组件传值
                        emit('parentsEmit', send);
                        visible.value = false
                    }).catch((error) => {
                        if (error.msg !== null) {
                            checkMsg.value = error.msg
                            centerDialogVisible1.value = true
                        }
                    });
                }
            }
        }
    })
}
// 参与组织
const deptTreeList = () => {
    deptTree().then((res) => {
        options1.value = res.data;
    });
};
//专业名称
const getProfessionalName = () => {
    professionalnameList().then((res) => {
        Object.assign(options2, res.data)
        // console.log("专业名称",options2);
    });
};
const getItem2 = (val: any) => {
    // console.log(val,'33333',keypointsListData)
    let names = []
    keypointsListData.forEach(item => {
        for (let i = 0; i < val.length; i++) {
            if (item.keyId == val[i]) {
                names.push(item.keyPoint)
            }
        }
    })
    queryForm.keyPoint = names
}
const getItem3 = (val: any) => {
    // console.log(val,'11111')
    let names = []
    options2.forEach(item => {
        for (let i = 0; i < val.length; i++) {
            if (item.zymcId == val[i]) {
                names.push(item.zymcName)
            }
        }
    })
    queryForm.zymcName = names
    // console.log('queryForm.zymcName',queryForm.zymcName,queryForm)
    queryForm.keyId = []
    getKeypointsList()
}
//关键点
const getKeypointsList = () => {
    keypointsListData.length = 0
    const ids = {
        zymcIds: queryForm.zymcId
    }
    // console.log(' queryForm----', ids,queryForm)
    getKeyPointListByZymcIds(ids).then((res: any) => {
        Object.assign(keypointsListData, res.data)
        // console.log(' queryForm----',  keypointsListData,queryForm)
    });
}
// 计算属性：每道题总分
const formatTotalScore = (row: { questionNum: number; mark: number }) => {
    row.markSum = row.questionNum * row.mark
    return row.questionNum * row.mark;
};
// 删除操作
const handleDelete = async (ids: string[]) => {
    try {
        await useMessageBox().confirm('此操作将永久删除');
    } catch {
        return;
    }
    try {
        await delObjs(ids);
        getDataList();
        useMessage().success('删除成功');
    } catch (err: any) {
        useMessage().error(err.msg);
    }
};
// 暴露变量
defineExpose({
    openDialog
});
</script>
<style lang="scss" scoped>
.el-form {
    margin-left: 15px;
}

.option {
    display: flex;
}

.answer {
    margin: -15px 0 0 30px
}

.line {
    border-top: 1px dashed #817B7B;
    width: 1270px;
    height: 0;
    margin-top: 10px;
    margin-left: -5px
}

.el-main {
    --el-main-padding: 0px !important;
}

.el-container {
    margin-top: -20px;
}

.mb20 {
    margin-bottom: 5px !important;
}
</style>
